package com.jn.zhinongbao.adapter;

import android.app.AlertDialog;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.supportingagriculturaltreasures.adapter.MerchantOrderAdapter;
import com.example.supportingagriculturaltreasures.bean.Order;
import com.example.supportingagriculturaltreasures.bean.User;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;
import com.example.supportingagriculturaltreasures.utils.PreferenceManager;

import java.util.ArrayList;
import java.util.List;

public class MerchantOrderActivity extends AppCompatActivity implements MerchantOrderAdapter.OnOrderActionListener {

    // 订单状态常量
    public static final int STATUS_PAID = 1;        // 已付款
    public static final int STATUS_PENDING = 2;     // 待发货
    public static final int STATUS_SHIPPED = 3;     // 已发货
    public static final int STATUS_CONFIRMED = 4;   // 确认收货
    public static final int STATUS_CANCELLED = 5;   // 已取消

    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private TextView tvEmpty;
    
    private MerchantOrderAdapter adapter;
    private List<Order> orderList;
    
    private PreferenceManager preferenceManager;
    private DatabaseHelper databaseHelper;
    private User currentUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_merchant_order);

        // 设置ActionBar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("订单管理");
        }

        initViews();
        initData();
        setupRecyclerView();
        loadOrders();
    }

    private void initViews() {
        recyclerView = findViewById(R.id.recycler_view);
        swipeRefreshLayout = findViewById(R.id.swipe_refresh);
        tvEmpty = findViewById(R.id.tv_empty);

        // 下拉刷新
        swipeRefreshLayout.setOnRefreshListener(this::loadOrders);
    }

    private void initData() {
        preferenceManager = new PreferenceManager(this);
        databaseHelper = new DatabaseHelper(this);
        orderList = new ArrayList<>();
        
        // 获取当前用户
        int userId = preferenceManager.getCurrentUserId();
        if (userId != -1) {
            currentUser = databaseHelper.getUserById(userId);
        }
    }

    private void setupRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MerchantOrderAdapter(orderList, this);
        recyclerView.setAdapter(adapter);
    }

    private void loadOrders() {
        if (currentUser == null) {
            Toast.makeText(this, "用户信息获取失败", Toast.LENGTH_SHORT).show();
            return;
        }

        // 根据商家ID获取订单
        List<Order> orders = databaseHelper.getOrdersByMerchantId(currentUser.getId());
        
        orderList.clear();
        orderList.addAll(orders);
        
        if (orderList.isEmpty()) {
            recyclerView.setVisibility(View.GONE);
            tvEmpty.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            tvEmpty.setVisibility(View.GONE);
        }
        
        adapter.updateOrders(orderList);
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadOrders(); // 从其他页面返回时刷新数据
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onOrderClick(Order order) {
        // 可以跳转到订单详情页
        Toast.makeText(this, "订单详情: " + order.getProductName(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onOrderLongClick(Order order) {
        showOrderStatusDialog(order);
    }

    private void showOrderStatusDialog(Order order) {
        String[] statusOptions = {
            "已付款",
            "待发货", 
            "已发货",
            "确认收货",
            "已取消"
        };
        
        int[] statusValues = {
            STATUS_PAID,
            STATUS_PENDING,
            STATUS_SHIPPED,
            STATUS_CONFIRMED,
            STATUS_CANCELLED
        };

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("修改订单状态")
                .setItems(statusOptions, (dialog, which) -> {
                    int newStatus = statusValues[which];
                    updateOrderStatus(order, newStatus);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void updateOrderStatus(Order order, int newStatus) {
        boolean success = databaseHelper.updateOrderStatus(order.getId(), newStatus);
        if (success) {
            Toast.makeText(this, "状态更新成功", Toast.LENGTH_SHORT).show();
            loadOrders(); // 刷新列表
        } else {
            Toast.makeText(this, "状态更新失败", Toast.LENGTH_SHORT).show();
        }
    }

    public static String getStatusText(int status) {
        switch (status) {
            case STATUS_PAID:
                return "已付款";
            case STATUS_PENDING:
                return "待发货";
            case STATUS_SHIPPED:
                return "已发货";
            case STATUS_CONFIRMED:
                return "确认收货";
            case STATUS_CANCELLED:
                return "已取消";
            default:
                return "未知状态";
        }
    }

    public static int getStatusColor(int status) {
        switch (status) {
            case STATUS_PAID:
                return 0xFF4CAF50; // 绿色
            case STATUS_PENDING:
                return 0xFFFF9800; // 橙色
            case STATUS_SHIPPED:
                return 0xFF2196F3; // 蓝色
            case STATUS_CONFIRMED:
                return 0xFF9C27B0; // 紫色
            case STATUS_CANCELLED:
                return 0xFFF44336; // 红色
            default:
                return 0xFF666666; // 灰色
        }
    }
} 